const db = require('../DB/sqlPool');

/**
 * 获取文章列表，支持分页、搜索、筛选
 * @param {Object} params
 * @param {string} params.title
 * @param {string|number} params.status
 * @param {number} params.page
 * @param {number} params.pageSize
 * @returns {Promise<{list: Array, total: number}>}
 */
async function getArticleList({ title = '', status = '', page = 1, pageSize = 10 }) {
  const where = ['a.is_deleted=0'];
  const values = [];
  if (title) {
    where.push('a.title LIKE ?');
    values.push(`%${title}%`);
  }
  if (status !== '' && status !== undefined) {
    where.push('a.status = ?');
    values.push(status);
  }
  const whereSql = where.length ? 'WHERE ' + where.join(' AND ') : '';
  const offset = (Number(page) - 1) * Number(pageSize);
  // 查询总数
  const totalSql = `SELECT COUNT(*) as total FROM shequ_article a ${whereSql}`;
  const totalRows = await db.queryData(totalSql, values);
  const total = totalRows[0]?.total || 0;
  // 查询列表
  const listSql = `
    SELECT a.*, u.username, u.avatar
    FROM shequ_article a
    LEFT JOIN shequ_user u ON a.user_id = u.id
    ${whereSql}
    ORDER BY a.created_at DESC
    LIMIT ?, ?
  `;
  const listResult = await db.queryData(listSql, [...values, offset, Number(pageSize)]);
  console.log('article list result:', listResult, Array.isArray(listResult.rows));
  // 兜底处理
  const defaultAvatar = '/default-avatar.png';
  const safeList = Array.isArray(listResult.rows) ? listResult.rows : [];
  return {
    list: safeList.map(item => ({
      id: item.id,
      title: item.title,
      status: item.status,
      username: item.username || '已注销',
      avatar: item.avatar || defaultAvatar,
      cover: '', // 可扩展为首图
      view_count: item.view_count == null ? 0 : item.view_count,
      created_at: item.created_at,
      user: { username: item.username || '已注销', avatar: item.avatar || defaultAvatar }
    })),
    total
  };
}

module.exports = {
  getArticleList
};
